package org.zk.controller;

import com.google.gson.Gson;
import org.zk.dto.CommentsAndInfosDto;
import org.zk.dto.PreOrders;
import org.zk.dto.SixGoodsByCatelogDto;
import org.zk.entity.*;
import org.zk.service.CatelogService;
import org.zk.service.GoodsService;
import org.zk.service.ImageService;
import org.zk.service.PurseService;
import org.zk.util.Msg;
import org.zk.util.UtilDate;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping(value = "/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private CatelogService catelogService;

    @Autowired
    private ImageService imageService;

    @Autowired
    private PurseService purseService;

    Gson gson = new Gson();

    /**
     * 首页商品列表（每类最多6个）status =1
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAllCateLog", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=utf-8")
    public String getAllCateLog() {

        List<SixGoodsByCatelogDto> sixGoodsByCatelog = goodsService.getSixGoodsByCatelog();

        Msg msg = new Msg(0);
        if (sixGoodsByCatelog != null) {
            msg.setCode(1);
            msg.setData(sixGoodsByCatelog);
        }

        return gson.toJson(msg);
    }

    /**
     * 获取每个分类下的全部商品（分页） status
     *
     * @param cateId 分类id
     * @param limit  每页条数
     * @param page   获取第几页
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getGoodsById", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=utf-8")
    public String getGoodsesById(@Param("cateId") Integer cateId, @Param("limit") Integer limit, @Param("page") Integer page) {

        Msg msg = new Msg(0, 0, "");
//        System.out.println("init cateid"+cateId);
        List<GoodsExt2> goodsById = goodsService.getGoodsesById(cateId, limit, page);
        Integer goodsesCountById = goodsService.getGoodsesCountById(cateId);

        msg.setCount(goodsesCountById);
        if (goodsById != null) {
            msg.setCode(1);

            msg.setData(goodsById);
        }
        return gson.toJson(msg);
    }

    /**
     * 根据商品id获取商品评论和卖家信息
     *
     * @param goodsId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getComAndInfos", method = {RequestMethod.POST}, produces = "text/plain;charset=utf-8")
    public String getComAndInfos(@Param("goodsId") Integer goodsId) {


        CommentsAndInfosDto dto = goodsService.getGoodsAndComAndInfoByGid(goodsId);

        Msg msg = new Msg(0, "");
        if (dto != null) {

            msg.setCode(1);
            msg.setData(dto);
        }
        return gson.toJson(msg);
    }

    /**
     * 用户发布商品（登录状态）
     *
     * @param name
     * @param price
     * @param real_price
     * @param cateId
     * @param describle
     * @param request
     * @param file
     * @return
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "/publishGoods", method = {RequestMethod.POST}, produces = "text/plain;charset=utf-8")
    public String publishGoods(String name, Float price, Float real_price, Integer cateId, String describle, HttpServletRequest request, @RequestParam("goodsImg") MultipartFile file) {

        //先封装goods信息 插入goods然后获得提交后的商品id 然后封装图片信息 提交图片
        Msg msg = new Msg(0);
        //判断分类id是否合理  当不存在的分类 直接返回
        List<Catelog> catelogList = catelogService.getCateLog();
        Set<Integer> cateIdSet = new HashSet<>();
        for (Catelog catelog : catelogList) {
            cateIdSet.add(catelog.getId());
        }
        Integer initSetLen = cateIdSet.size();
        cateIdSet.add(cateId);
        //添加后长度变化 说明添加了新的
        if (cateIdSet.size() > initSetLen) {
            return gson.toJson(msg);
        }

//      判断用户id
        User currentUser = (User) request.getSession().getAttribute("currentUser");
//      System.out.println(currentUser);
        if (currentUser == null) {
            msg.setMessage("用户未登录");
            return gson.toJson(msg);

        }

        Goods publishGood = new Goods();
        publishGood.setName(name);
        publishGood.setPrice(price);
        publishGood.setRealPrice(real_price);
        publishGood.setUserId(currentUser.getId());
        publishGood.setCatelogId(cateId);
        String currentDateTime = UtilDate.getCurrentDateStrYMD();
        publishGood.setStartTime(currentDateTime);
        publishGood.setPolishTime(currentDateTime);
        publishGood.setDescrible(describle);
        publishGood.setStatus(1);

        Integer rst = goodsService.addGoods(publishGood);
//        System.out.println("id" +rst);

        if (rst > 0) {

            Integer goodsId = publishGood.getId();
            System.out.println("goodsId" + goodsId);
            //先封装部分 imge对象
            Image image = new Image();
            image.setGoodsId(goodsId);
            Integer rst2 = imageService.addImage(image, request, file);
            if (rst2 > 0) {
                msg.setCode(1);
            }
        }
        return gson.toJson(msg);
    }

    /**
     * 搜索商品
     *
     * @param goodsInfo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchGoods", method = {RequestMethod.POST}, produces = "text/plain;charset=utf-8")
    public String searchGoods(@Param("goodsInfo") String goodsInfo, @RequestParam("limit") Integer limit, @RequestParam("page") Integer page) {

        Msg msg = new Msg(0);
        //判断分类id是否合理  当不存在的分类 直接返回
        List<GoodsExt2> searchedGoods = goodsService.searchGoods(goodsInfo, limit, page);
        if (searchedGoods != null) {
            msg.setCode(1);
            msg.setCount(goodsService.getCountGoodsByNameOrDesc(goodsInfo));
            msg.setData(searchedGoods);
            return gson.toJson(msg);
        }

        return gson.toJson(msg);
    }

    /**
     * 查看用户发布的商品（登录状态）
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/myIdleGoods", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=utf-8")
    public String myIdleGoods(HttpServletRequest request) {

        Msg msg = new Msg(0);
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        if (currentUser == null) {
            msg.setMessage("未登录");
            return gson.toJson(msg);
        }
        Integer userId = currentUser.getId();
        List<GoodsExt2> goodsList = goodsService.getGoodsesByUid(userId);

        if (goodsList != null) {
            msg.setCode(1);
            msg.setData(goodsList);

        }
        return gson.toJson(msg);
    }


    /**
     * 删除我的闲置
     * <p>
     * (登录状态才可以下架自己的商品)
     *
     * @param goodsId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/removeGoods", method = {RequestMethod.POST}, produces = "text/plain;charset=utf-8")
    public String removeGoods(Integer goodsId, HttpServletRequest request) {

        Msg msg = new Msg(0);
        Goods goodsByPrimaryKey = goodsService.getGoodsByPrimaryKeyWithoutStatus(goodsId);

        if (goodsByPrimaryKey == null) {
            msg.setMessage("没有此商品");
            return gson.toJson(msg);
        }

        Integer rst = goodsService.rmGoods(goodsId);

        if (rst > 0) {
            msg.setCode(1);
        }
        return gson.toJson(msg);
    }

    /**
     * 购买商品（登录状态）
     * 生成预订单
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/buyGoods", method = {RequestMethod.POST}, produces = "text/plain;charset=utf-8")
    public String buyGoods(HttpServletRequest request, Integer goodsId) {

        Msg msg = new Msg(0);
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        if (currentUser == null) {
            msg.setMessage("用户未登录");
            return gson.toJson(msg);
        }
        if (currentUser != null) {
            Goods goods = goodsService.getGoodsByPrimaryKey(goodsId);
            if (goods != null) {
                PreOrders preOrders = goodsService.getPreOrders(currentUser.getId(), goodsId);
                if (preOrders != null) {
                    msg.setCode(1);
                    msg.setData(preOrders);
                    return gson.toJson(msg);
                }
            } else {
                msg.setCode(0);
                msg.setMessage("商品不存在或者已经下架");
                return gson.toJson(msg);
            }
        }
        return gson.toJson(msg);
    }

    /**
     * 生成订单
     *
     * @param request
     * @param orders
     * @return
     */
    //生成订单  orderNum goodsId order_information
    @ResponseBody
    @RequestMapping(value = "/addOrder", method = {RequestMethod.POST}, produces = "text/plain;charset=utf-8")
    public String addOrder(HttpServletRequest request, Orders orders) {

        Msg msg = new Msg(0);
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        if (currentUser == null) {
            msg.setMessage("用户未登录");
            return gson.toJson(msg);
        }
        orders.setUserId(currentUser.getId());
        Integer rst = goodsService.addOrders(orders);
        if (rst != null && rst > 0) {

//          生成订单商品下架
            Integer rst2 = goodsService.withdrawGoods(orders.getGoodsId());
            Goods goods = goodsService.getGoodsByPrimaryKeyWithoutStatus(orders.getGoodsId());
            if (goods != null) {
        //          买家减少钱
                Integer rst3 = purseService.rechargePurse(currentUser.getId(), goods.getPrice() * (-1));
                //          卖家增加钱
                Integer rst4 = purseService.rechargePurse(goods.getUserId(), goods.getPrice());
                if (rst2 != null  && rst3!=null && rst4!=null &&rst2 > 0&&rst3>0&&rst4>0) {
                    msg.setCode(1);
                    return gson.toJson(msg);
                }
            }
        }

        return gson.toJson(msg);

    }


}
